/**
 * @author lijuan wang
 * print CallGraph Dot
 */
package com.ss.cg;

import java.io.FileWriter;
import java.io.IOException;

import com.ss.cg.CallGraph;
import com.ss.cg.CallGraphNode;
import com.ss.cg.CallSite;

public class PrintCGDot implements IPrintCG {
	private String path;
	public String getPath() {
		return path;
	}
	public PrintCGDot(String path){
		this.path=path;
	}
	private FileWriter dotName;

	public FileWriter getDotName() {
		return dotName;
	}

	public void setDotName(FileWriter dotName) {
		this.dotName = dotName;
	}
	/**
	 * visit CallGraphNode
	 * @param node
	 * @see CallGraphNode
	 */
	public void visit(CallGraphNode node){
		try {
			
			this.dotName.write(node.getId() + "[style="+node.getStyle()+" , color="+node.getColor()+" ,label=\"" + node.getIdentifier().replace("\"", "'") +"\"" + "];\n");
			
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	/**
	 * visit CallSite
	 * @param edge
	 * @see CallSite
	 */
	public void visit(CallSite edge){
		try {
			String s = "";
			s = edge.getCaller().getId()+ " -> " + edge.getCallee().getId()+"[color=blue]";
			s = s + "\n";
			this.dotName.write(s);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	/**
	 *visit CallGraph
	 * @param g
	 * @see CallGraph
	 * @param path
	 */
	public void visit(CallGraph g){
		try{
			this.dotName = new FileWriter(this.path +g.getName() + "_CG.dot");
			this.dotName.write("digraph G {\n");
			for (CallGraphNode node : g.getNodes()) {
				visit(node);
			}
			for (CallSite edge : g.getEges()) {
				visit(edge);
			}
			this.dotName.write(" }");
			this.dotName.close();
			String name = path+g.getName();
			try {
				java.lang.Runtime.getRuntime().exec(
						"dot -Tjpg -o " + name + "_CG.jpg " + name + "_CG.dot")
						.waitFor();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (InterruptedException e2) {
				e2.printStackTrace();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
